<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>P208 9.2.3 【案例】限定输入内容</title>
</head>

<body>
    <form id="form">
        年度<input type="text" name="year">
        月份<input type="text" name="month">
        <input type="submit" value="查询">
    </form>
    <div id="result"></div>
    <script>
        var form = document.getElementById('form');
        var result = document.getElementById('result');
        var inputs = document.getElementsByTagName('input');
        form.onsubmit = function () {
            return checkYear(inputs.year) && checkMonth(inputs.month);
        };
        function checkYear(obj) {
            if (!obj.value.match(/^\d{4}$/)) {
                obj.style.borderColor = 'red';
                result.innerHTML = '输入错误，年份为4位数字表示';
                return false;
            }
            result.innerHTML = '';
            return true;
        }
        function checkMonth(obj) {
            if (!obj.value.match(/^((0?[1-9])|(1[012]))$/)) {
                obj.style.borderColor = 'red';
                resule.innerHTML = '输入错误，月份为1~12之间';
                return false;
            }
            result.innerHTML = '';
            return true;
        }
        inputs.year.onfocus = function () {
            this.style.borderColor = '';
        };
        inputs.month.onfocus = function () {
            this.style.borderColor = '';
        };
        inputs.year.onblur = function () {
            this.value = this.value.trim();
            checkYear(this);
        };
        inputs.month.onblur = function () {
            this.value = this.value.trim();
            checkMonth(this);
        };
        if (!String.prototype.trim) {
            String.prototype.trim = function () {
                return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
            };
        }
    </script>
    <a href="../首页/page09.html">
        <h2>返回上一页面</h2>
    </a>
</body>

</html>